package by.bsu.scs.util.filter;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import by.bsu.scs.model.User;
import by.bsu.scs.util.manager.SessionManager;

/**
 * @author Alexey Hursevich
 * @version 1.0
 * 
 * Responsible for setting ecoding and locale.
 */
public class EncodingFilter implements Filter {
	
	private static final String PARAM_LOCALE = "locale";
	private static final String LOC_RU = "ru";
	private static final String LOC_EN = "en";
	
	private FilterConfig config;

	/**
	 * Sets character encoding and user locale.
	 * <p>
	 * Ecoding parameter is defined in web.xml file.
	 * <p>
	 * If user instance is not found in session context - locale is Russian by default. 
	 * If session attribute 'localization' is null, method checks user localization
	 * preference stored in DB.
	 * 
	 * @param request
     * @param response
     * 
     * @param chain
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//Setting request encoding
		request.setCharacterEncoding(config.getInitParameter("encoding"));
		
		//Setting localization
		HttpSession session = ((HttpServletRequest) request).getSession();
		String localization = (String) session.getAttribute(PARAM_LOCALE);
		
		User user = SessionManager.getInstance().getUser((HttpServletRequest) request);
		
		if(user == null) {
			session.setAttribute( "org.apache.struts.action.LOCALE", new Locale( LOC_RU ) );
		}
		else if(localization == null && user.getLocalization() != null) {
			String locale = user.getLocalization().getDefaultLocale();
			session.setAttribute( "org.apache.struts.action.LOCALE", new Locale( locale ) );
			session.setAttribute( PARAM_LOCALE, locale );
		}
		else if( localization != null ) {
			session.setAttribute( "org.apache.struts.action.LOCALE", new Locale( localization ) );
		}
		
		chain.doFilter(request, response);	
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}
}